package com.example.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Account;
import com.example.entity.Asset;
import com.example.entity.Assetinfo;
import com.example.mapper.AssetMapper;
import com.example.mapper.AssetinfoMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.util.List;

@Service
public class AssetinfoService {

    @Resource
    AssetinfoMapper assetinfoMapper;
    @Resource
    AssetMapper assetMapper;

    public void add(Assetinfo assetinfo) {
        assetinfo.setStatus("待审核");
        assetinfo.setTime(DateUtil.now());
        assetinfoMapper.insert(assetinfo);
        // 图书数量减一
        Asset asset = assetMapper.selectById(assetinfo.getAssetId());
        if (ObjectUtil.isNotEmpty(asset)) {
            asset.setNum(asset.getNum() - 1);
            assetMapper.updateById(asset);
        }
    }

    public void update(Assetinfo assetinfo) {
        assetinfoMapper.updateById(assetinfo);
        Account currentUser = TokenUtils.getCurrentUser();
        if ("ADMIN".equals(currentUser.getRole()) && "审核拒绝".equals(assetinfo.getStatus())) {
            // 图书归还
            Asset asset = assetMapper.selectById(assetinfo.getAssetId());
            if (ObjectUtil.isNotEmpty(asset)) {
                asset.setNum(asset.getNum() + 1);
                assetMapper.updateById(asset);
            }
        }
    }

    public void deleteById(Integer id) {
        assetinfoMapper.deleteById(id);
    }

    public List<Assetinfo> selectAll(Assetinfo assetinfo) {
        return assetinfoMapper.selectAll(assetinfo);
    }

    public PageInfo<Assetinfo> selectPage(Integer pageNum, Integer pageSize, Assetinfo assetinfo) {
        Account currentUser = TokenUtils.getCurrentUser();
        if ("USER".equals(currentUser.getRole())) {
            assetinfo.setUserId(currentUser.getId());
        }
        // 开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Assetinfo> list = assetinfoMapper.selectAll(assetinfo);
        return PageInfo.of(list);
    }
}
